package imageProcessing.filter;

import imageProcessing.DualImageListener;
import imageProcessing.Duplicator;
import imageProcessing.ImageEvent;
import imageProcessing.ImageListener;

import java.awt.image.renderable.ParameterBlock;
import java.util.ArrayList;

import javax.media.jai.JAI;
import javax.media.jai.PlanarImage;

public class AndFilter implements DualImageListener {

	private ArrayList<ImageListener> _listeners;

	private PlanarImage _leftImage;
	private PlanarImage _rightImage;
	private PlanarImage _targetImage;
	
	public AndFilter(){
		_listeners = new ArrayList<ImageListener>();
		
		_leftImage = null;
		_rightImage = null;
		_targetImage = null;
	}

	public void notifyListeners() {
		ImageEvent ie  = new ImageEvent(this, _targetImage);
		ArrayList<ImageListener> copy = Duplicator.copyListeners(_listeners);
		for (ImageListener listener : copy) {
			listener.imageChanged(ie);
		}
	}
	
	@Override
	public void leftImageChanged(ImageEvent ie) {
		
		if(_rightImage == null){
			_rightImage = ie.getImage();
		}
		
		_leftImage = ie.getImage();
		ParameterBlock pb = new ParameterBlock();
		pb.addSource(_rightImage);          // The first image
		pb.addSource(_leftImage);          // The second image
		_targetImage = JAI.create("and", pb);
		notifyListeners();
	}

	@Override
	public void rightImageChanged(ImageEvent ie) {
		if(_leftImage == null){
			_leftImage = ie.getImage();
		}
		
		_rightImage = ie.getImage();
		ParameterBlock pb = new ParameterBlock();
		pb.addSource(_rightImage);          // The first image
		pb.addSource(_leftImage);          // The second image
		_targetImage = JAI.create("and", pb);
		notifyListeners();
	}
	
	public void addImageListener(ImageListener il){
		_listeners.add(il);
	}
	
	public void removeImageListener(ImageListener il){
		_listeners.remove(il);
	}
}
